package edu.ynu.se.xiecheng.achitectureclass.Demo1.service;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import java.io.*;
import java.time.LocalDateTime;
import java.util.Map;

@Service
public class AccessTokenService {

    private String accessToken; // 当前Token
    private LocalDateTime expiryTime; // Token过期时间
    private final RestTemplate restTemplate = new RestTemplate();

    private static final String TOKEN_URL = "https://fbox360.com/idserver/core/connect/token";
    private static final String CLIENT_ID = "68db2e8bda8d47b5b5db7eaf71c7dcdd";
    private static final String CLIENT_SECRET = "76dc724c95004acab25482d344dab407";
    private static final String SCOPE = "fbox";

    /**
     * 初始化方法，服务启动时自动调用
     */
    @PostConstruct
    public void initializeToken() {
        loadTokenFromFile(); // 尝试从文件加载Token
        if (accessToken == null || LocalDateTime.now().isAfter(expiryTime)) {
            refreshToken(); // 如果Token无效，重新获取
        }
    }

    /**
     * 从文件加载Token和过期时间
     */
    private void loadTokenFromFile() {
        String path = "src/main/java/edu/ynu/se/xiecheng/achitectureclass/Demo1/token.txt";

        try (BufferedReader reader = new BufferedReader(new FileReader(path))) {
            this.accessToken = reader.readLine(); // 读取第一行作为 accessToken
            this.expiryTime = LocalDateTime.parse(reader.readLine()); // 读取第二行作为 expiryTime
            System.out.println("Token 和过期时间已成功从文件加载。");
        } catch (FileNotFoundException e) {
            System.out.println("Token 文件未找到，尝试重新获取 Token...");
            refreshToken(); // 如果文件不存在，则重新获取 Token
        } catch (IOException e) {
            System.err.println("读取 Token 文件失败：" + e.getMessage());
            e.printStackTrace();
        } catch (Exception e) {
            System.err.println("解析 Token 文件失败，可能文件格式错误：" + e.getMessage());
            e.printStackTrace();
        }
    }


    /**
     * 刷新Token的逻辑
     */
    private void refreshToken() {
        String body = String.format(
                "client_id=%s&client_secret=%s&grant_type=client_credentials&scope=%s",
                CLIENT_ID, CLIENT_SECRET, SCOPE
        );

        HttpHeaders headers = new HttpHeaders();
        headers.set("Content-Type", "application/x-www-form-urlencoded");

        HttpEntity<String> request = new HttpEntity<>(body, headers);

        System.out.println(accessToken);
        try {
            ResponseEntity<Map> response = restTemplate.postForEntity(TOKEN_URL, request, Map.class);

            if (response.getBody() != null) {
                Map<String, Object> responseData = response.getBody();
                this.accessToken = (String) responseData.get("access_token");
                int expiresIn = (int) responseData.get("expires_in");
                this.expiryTime = LocalDateTime.now().plusSeconds(expiresIn - 60); // 提前60秒刷新
                saveTokenToFile(); // 保存Token到文件
            }
        } catch (Exception e) {
            throw new RuntimeException("刷新Token时出错", e);
        }
    }

    /**
     * 保存Token到文件
     */
    private void saveTokenToFile() {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter("src/main/java/edu/ynu/se/xiecheng/achitectureclass/Demo1/token.txt"))) {
            writer.write(accessToken + "\n");
            writer.write(expiryTime.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取当前Token
     */
    public String getToken() {
        if (LocalDateTime.now().isAfter(expiryTime)) {
            refreshToken();
        }
        return accessToken;
    }
}
